package com.sound.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.hoangkien.config.SoundCloudConfig;
import com.hoangkien.entity.SoundCloudEntity;
import com.hoangkien.entity.UserEntity;
import com.hoangkien.service.SoundCloudService;
import com.hoangkien.service.UserService;
import com.hoangkien.util.JSONParser;
import com.hoangkien.util.StreamUtils;
import com.hoangkien.util.TestWifiConnected;

public class GetDataCloud extends AsyncTask<String, String, JSONObject> {
	private Context context;
	Boolean isConnectionExist = false; // test wifi
	TestWifiConnected cd;
	
	private String url = "";
	private int limit;
	private int offset;
	private String q;
	
	String jsonString;
	ArrayList<SoundCloudEntity> listSound = new ArrayList<SoundCloudEntity>();
	ArrayList<UserEntity> listuser = new ArrayList<UserEntity>();

	public GetDataCloud(Context context, int limit, int offset, String q) {
		this.context = context;
		this.limit = limit;
		this.offset = offset;
		this.q = q;
		url = "https://api.soundcloud.com/tracks/?filter=streamable&client_id="
				+ SoundCloudConfig.CLIENT_ID + "&format="
				+ SoundCloudConfig.FORMAT + "&limit=" + limit + "&offset="
				+ offset + "&q=" + q + "&order=hotness";
	}


	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected JSONObject doInBackground(String... params) {
		cd = new TestWifiConnected(context);
		isConnectionExist = cd.checkMobileInternetConnection();
		if(isConnectionExist){  //co Internet
			JSONParser jparser = new JSONParser();
			jsonString = jparser.getJSONFromUrl(url);
			try {
				 HttpClient client = new DefaultHttpClient();
				 HttpUriRequest request = new HttpGet(url);
				 HttpResponse response = client.execute(request);
				 String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
				 JSONArray jsonArr = new JSONArray(jsonString);
				 for (int i = 0; i < jsonArr.length(); i++) {
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					 String kind = jsonObj.getString("kind");   
					 int id = jsonObj.getInt("id");
					 String created_at = jsonObj.getString("created_at");
					 int user_id= jsonObj.getInt("user_id");
					 int duration= jsonObj.getInt("duration");
					 boolean commentable = jsonObj.getBoolean("commentable");
					 String state = jsonObj.getString("state");
					 int original_content_size= jsonObj.getInt("original_content_size");
					 String last_modified = jsonObj.getString("last_modified");
					 String sharing = jsonObj.getString("sharing");
					 String tag_list = jsonObj.getString("tag_list");
					 String permalink = jsonObj.getString("permalink");
					 boolean streamable = jsonObj.getBoolean("streamable");
					 String embeddable_by = jsonObj.getString("embeddable_by");
					 boolean downloadable = jsonObj.getBoolean("downloadable");
					 String purchase_url = jsonObj.getString("purchase_url");
					 String label_id = jsonObj.getString("label_id");;
					 String purchase_title = jsonObj.getString("purchase_title");
					 String genre = jsonObj.getString("genre");
					 String title = jsonObj.getString("title");
					 String description = jsonObj.getString("description");
					 String label_name = jsonObj.getString("label_name");
					 String release = jsonObj.getString("release");
					 String track_type = jsonObj.getString("track_type");
					 String key_signature = jsonObj.getString("key_signature");
					 String isrc = jsonObj.getString("isrc");
					 String video_url = jsonObj.getString("video_url");
					 String bpm = jsonObj.getString("bpm");
					 String release_year = jsonObj.getString("release_year");
					 String release_month = jsonObj.getString("release_month");
					 String release_day = jsonObj.getString("release_day");
					 String original_format = jsonObj.getString("original_format");
					 String license = jsonObj.getString("license");
					 String uri = jsonObj.getString("uri");
					 String permalink_url = jsonObj.getString("permalink_url");
					 String artwork_url = jsonObj.getString("artwork_url");
					 String waveform_url = jsonObj.getString("waveform_url");
					 String stream_url = jsonObj.getString("stream_url");
					 int playback_count= jsonObj.getInt("playback_count");
					 int download_count= jsonObj.getInt("download_count");
					 int favoritings_count= jsonObj.getInt("favoritings_count");
					 int comment_count= jsonObj.getInt("comment_count");
					 String attachments_uri = jsonObj.getString("attachments_uri");
					 String policy = jsonObj.getString("policy");
					 
					 JSONObject jo = jsonArr.getJSONObject(i).getJSONObject("user");
					 int id1 = jo.getInt("id");
					 String kind1 = jo.getString("kind");
					 String permalink1 = jo.getString("permalink");;
					 String username1 = jo.getString("username");;
					 String last_modified1 = jo.getString("last_modified");;
					 String uri1 = jo.getString("uri");;
					 String permalink_url1 = jo.getString("permalink_url");;
					 String avatar_url1 = jo.getString("avatar_url");;
					 
					 UserEntity userEntity = new UserEntity(id1, kind1, permalink1, username1, last_modified1, uri1, permalink_url1, avatar_url1);
					 SoundCloudEntity soundentity = new SoundCloudEntity(kind, id, created_at, user_id, duration, commentable, state, original_content_size, last_modified, sharing, tag_list, permalink, streamable, embeddable_by, downloadable, purchase_url, label_id, purchase_title, genre, title, description, label_name, release, track_type, key_signature, isrc, video_url, bpm, release_year, release_month, release_day, original_format, license, uri, userEntity, permalink_url, artwork_url, waveform_url, stream_url, playback_count, download_count, favoritings_count, comment_count, attachments_uri, policy);
					 listuser.add(userEntity);
					 listSound.add(soundentity);
				 }
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		} else { }
		return null;
	}

	@Override
	protected void onPostExecute(JSONObject result) {
		UserService userService = new UserService(context);
		SoundCloudService soundcloudService = new SoundCloudService(context);
		userService.deleteUser();
		soundcloudService.deleteSoundCloud();
		//insert vao cơ sở dữ liệu
		for (int i = 0; i < listuser.size(); i++) {
	    	userService.insert_user(listuser.get(i));
		}
		for (int i = 0; i < listSound.size(); i++) {
			soundcloudService.insert_soundCloud(listSound.get(i));
		}
		
		Intent intent = new Intent(SoundCloudConfig.BROADCAST_LOAD_DATA);
		context.sendBroadcast(intent);
	}
	

}
